//
//  NewFeatureViewController.swift
//  blog01
//
//  Created by 秦兴华 on 15/9/9.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
//常量定义在类外面
///可重用标识符
private let HMNFCellID = "HMReuseCellID"

//cell 数量
private let HMNFCellCount = 4

class NewFeatureViewController: UICollectionViewController {

    /// 构造函数调用父类构造函数设置布局
    init(){
        //UICollectionViewFlowLayout 的 flow
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册可重用cell：UICollectionViewCell.self 重点记忆，自定义cell的时候要修改这里
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: HMNFCellID)
        printLog(view)
        prepareLayout()
    }

    /// 准备布局
    private func prepareLayout(){
        //定义布局属性
        let layout = collectionView?.collectionViewLayout as!UICollectionViewFlowLayout
        
        //cell大小
//        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.itemSize = view.bounds.size
        
        //cell最小列间距
        layout.minimumInteritemSpacing = 0
        
        //cell 最小行间距
        layout.minimumLineSpacing = 0
            
        //滚动方向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        //分页[scrollView 属性]
        collectionView?.pagingEnabled = true
        
        //弹簧效果
        collectionView?.bounces = false
        
        //隐藏水平滚动条
        collectionView?.showsHorizontalScrollIndicator = false
        
    }
    // MARK: - UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMNFCellCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
       
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMNFCellID, forIndexPath: indexPath) as! NewFeatureCell

//        cell.backgroundColor = indexPath.item%2==1 ? UIColor.blueColor():UIColor.greenColor()
        cell.imageIndex = indexPath.item
        
        return cell
    }
    
    // MARK: - UICollectionViewDelegate cell停止滑动时调用
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        //获取当前cell的indexPath
        let path = collectionView.indexPathsForVisibleItems().last!
        
        if path.item == (HMNFCellCount - 1){
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            cell.setButtonAnim()
        }
    }
}

/// 新特性 Cell，
//private保证 cell 只被当前控制器使用,
//里面的属性定义为private也可以被本文件调用到
//监听方法可以不加private，但是@objc必须加
private class NewFeatureCell : UICollectionViewCell{
    
    /// 图像索引属性
    var imageIndex : Int = 0{
       
        didSet{
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            self.startBtn.hidden = true
        }
    }
    
    /// 纯代码代码会调用
    //此时cell的frame已经在设置layout的 itemSize中进行了设置，已经有值
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    /// xib 和 SB 开发调用
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        
        setupUI()
    }
   
    /// 设置体验按钮监听方法
    @objc func startBtnClick(){
        print("开始体验")
    }
   
    /// 设置按钮动画
    private func setButtonAnim(){
       
        self.startBtn.hidden = false
        
        startBtn.transform = CGAffineTransformMakeScale(0, 0)
        
        //duration:动画时长 
        //usingSpringWithDamping:弹性系数 0 ~ 1越小越弹
        //initialSpringVelocity 初始速度
        UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options:[], animations: { () -> Void in
            self.startBtn.transform = CGAffineTransformIdentity
            }) { (complete) -> Void in
        }
    }

    /// 设置界面元素
    private func setupUI(){
        addSubview(iconView)
        addSubview(startBtn)
        
        iconView.frame = bounds
        
        //MARK: - 设置体验按钮布局
        startBtn.translatesAutoresizingMaskIntoConstraints = false
        //水平居中
        addConstraint(NSLayoutConstraint(item: startBtn, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))

        //下端据cell底部 160
        addConstraint(NSLayoutConstraint(item: startBtn, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
    }
    
    ///懒加载控件
    //新特性图片
    private lazy var iconView = UIImageView()
   
    //体验按钮
    private lazy var startBtn : UIButton = {
        let button  = UIButton()
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
       button.addTarget(self, action:"startBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        //自适应大小
        button.sizeToFit()
        return button
    
    }()
}
